<template>
  <div class="post-product">
    <div class="title">发布房源</div>
    <div class="pro-info">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
        <el-form-item label="房源标题" prop="title">
          <el-input v-model="ruleForm.title" placeholder="上架房源的标题"></el-input>
        </el-form-item>

        <el-form-item label="小区名或楼盘" prop="estateName">
          <el-autocomplete style="width: 470px" v-model="ruleForm.estateName" :fetch-suggestions="querySearch" placeholder="请输入小区名或楼盘" :trigger-on-focus="false" @select="handleSelect" @clear="ruleForm.estateId = ''" @change="ruleForm.estateId = ''"></el-autocomplete>
        </el-form-item>

        <el-form-item label="栋阁房号" prop="houseNum">
          <el-input v-model="ruleForm.houseNum" placeholder="请输入楼阁房号"></el-input>
        </el-form-item>

        <el-form-item label="房源总价" prop="sup">
          <el-input v-model="ruleForm.sup" placeholder="请输入房源总价" autocomplete="off" onkeyup="value=value.replace(/[^\d\.]/g,'')"><span slot="suffix">万元</span></el-input>
        </el-form-item>

        <el-form-item label="建筑面积" prop="builtArea">
          <el-input v-model="ruleForm.builtArea" placeholder="请输入房源的建筑面积" autocomplete="off" onkeyup="value=value.replace(/[^\d\.]/g,'')"><span slot="suffix">㎡</span></el-input>
        </el-form-item>

        <el-form-item label="套内面积" prop="insideArea">
          <el-input v-model="ruleForm.insideArea" placeholder="请输入房源的套内面积" autocomplete="off" onkeyup="value=value.replace(/[^\d\.]/g,'')"><span slot="suffix">㎡</span></el-input>
        </el-form-item>

        <el-form-item label="建成年代" prop="builtYear">
          <el-input v-model="ruleForm.builtYear" type="text" placeholder="请输入建成年代" onkeyup="value=value.replace(/[^\d]/g,'')"><span slot="suffix">年</span></el-input>
        </el-form-item>

        <el-form-item label="房源户型" prop="kind">
          <el-input v-model="ruleForm.kind1" style="width: 140px; margin-right: 25px;" onkeyup="value=value.replace(/[^\d]/g,'')">
            <span slot="suffix">室</span>
          </el-input>
          <el-input v-model="ruleForm.kind2" style="width: 140px; margin-right: 25px;" onkeyup="value=value.replace(/[^\d]/g,'')">
            <span slot="suffix">厅</span>
          </el-input>
          <el-input v-model="ruleForm.kind3" style="width: 140px" onkeyup="value=value.replace(/[^\d]/g,'')">
            <span slot="suffix">卫</span>
          </el-input>
        </el-form-item>

        <el-form-item label="装修" prop="decoration">
          <el-radio-group v-model="ruleForm.decoration">
            <el-radio label="毛坯"></el-radio>
            <el-radio label="普装"></el-radio>
            <el-radio label="精装"></el-radio>
            <el-radio label="豪装"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="房源楼层" prop="floor">
          <el-radio-group v-model="ruleForm.floor1">
            <el-radio label="低楼层"></el-radio>
            <el-radio label="中楼层"></el-radio>
            <el-radio label="高楼层"></el-radio>
          </el-radio-group>
          <span v-show="ruleForm.floor1" class="floor">
            共<el-input v-model="ruleForm.floor2" placeholder="几" autocomplete="off" onkeyup="value=value.replace(/[^\d]/g,'')">
            </el-input>层
          </span>
        </el-form-item>

        <el-form-item label="房源朝向" prop="orientation">
          <el-radio-group v-model="ruleForm.orientation">
            <el-radio label="东"></el-radio>
            <el-radio label="南"></el-radio>
            <el-radio label="西"></el-radio>
            <el-radio label="北"></el-radio>
            <el-radio label="东南"></el-radio>
            <el-radio label="东北"></el-radio>
            <el-radio label="西南"></el-radio>
            <el-radio label="南北"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="房源用途" prop="purpose">
          <el-radio-group v-model="ruleForm.purpose">
            <el-radio label="普通住宅"></el-radio>
            <el-radio label="写字楼"></el-radio>
            <el-radio label="商铺"></el-radio>
            <el-radio label="教育"></el-radio>
            <el-radio label="车位"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="产权性质" prop="nature">
          <el-input v-model="ruleForm.nature" style="width: 100;" placeholder="请输入房源的产权性质"></el-input>
        </el-form-item>

        <el-form-item label="产权年限" prop="propertyYear">
          <el-input v-model="ruleForm.propertyYear" onkeyup="value=value.replace(/[^\d]/g,'')" placeholder="请输入房源的产权年限"></el-input>
        </el-form-item>

        <el-form-item label="精选好房" prop="tag1">
          <el-radio-group v-model="ruleForm.tag1">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="满几年" prop="tag2_1">
          <el-radio-group v-model="ruleForm.tag2_1">
            <el-radio label="满一">满一年</el-radio>
            <el-radio label="满两">满两年</el-radio>
            <el-radio label="满三">满三年</el-radio>
            <el-radio label="满四">满四年</el-radio>
            <el-radio label="满五">满五年</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否唯一" prop="tag2_2">
          <el-radio-group v-model="ruleForm.tag2_2">
            <el-radio :label="1">唯一</el-radio>
            <el-radio :label="0">不唯一</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="红本在手" prop="tag3">
          <el-radio-group v-model="ruleForm.tag3">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="有电梯" prop="tag4">
          <el-radio-group v-model="ruleForm.tag4">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="随时可看" prop="tag5">
          <el-radio-group v-model="ruleForm.tag5">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="附近门店" prop="branch">
          <el-input class="area-box" v-model="ruleForm.branch" placeholder="请输入房源附近的线下门店"></el-input>
        </el-form-item>

        <el-form-item label="房源亮点" prop="lights_desc">
          <el-input class="area-box" type="textarea" v-model="ruleForm.lights_desc" placeholder="房源亮点介绍"></el-input>
        </el-form-item>

        <el-form-item label="装修简介" prop="dec_desc">
          <el-input class="area-box" type="textarea" v-model="ruleForm.dec_desc" placeholder="房源装修介绍"></el-input>
        </el-form-item>

        <el-form-item label="户型简介" prop="kind_desc">
          <el-input class="area-box" type="textarea" v-model="ruleForm.kind_desc" placeholder="房源户型介绍"></el-input>
        </el-form-item>

        <el-form-item label="附近交通" prop="traffic">
          <el-input class="area-box" type="textarea" v-model="ruleForm.traffic" placeholder="房源附近交通介绍"></el-input>
        </el-form-item>

        <el-form-item label="房源图片" prop="img">
          <UploaderFile @upload="upload($event, 'img')" :img-src="ruleForm.img"></UploaderFile>
        </el-form-item>
        <!-- 
        <el-form-item label="详情图片" prop="imgList">
          <UploaderFile
            @upload="upload($event, 'imgList')"
            :img-src="ruleForm.imgList"
          ></UploaderFile>
        </el-form-item> -->

        <el-form-item label="委托人姓名" prop="userName">
          <el-input v-model="ruleForm.userName" placeholder="委托人姓名"></el-input>
        </el-form-item>

        <el-form-item label="委托人手机号" prop="userPhone">
          <el-input v-model="ruleForm.userPhone" placeholder="委托人手机号" onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" v-if="!isEdit" @click="submitForm('ruleForm')">确认提交</el-button>
          <el-button type="warning" v-else @click="saveEditData('ruleForm')">保存信息</el-button>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script>
import "@/assets/less/b_post-product.less";
import Data from "@/assets/js/data";
import UploaderFile from '@/components/UploaderFile.vue'
export default {
  name: "PostHouse",
  data() {
    return {
      isEdit: false,
      areaData: [],
      estateList: [],// 存放小区

      ruleForm: {
        id: "",
        title: "",
        estateName: "",
        estateId: "",
        houseNum: '',
        sup: '',
        builtArea: '',
        insideArea: '',
        kind1: "",
        kind2: "",
        kind3: "",
        floor1: "",
        floor2: '',
        orientation: "",
        builtYear: "",
        decoration: "",
        branch: "",
        purpose: "",// 用途
        nature: "",// 产权性质
        propertyYear: '',// 产权年限
        sellingTime: "",
        tag1: 0,
        tag2_1: "",
        tag2_2: 0,
        tag3: 0,
        tag4: 0,
        tag5: 0,
        lights_desc: "",
        dec_desc: "",
        kind_desc: "",
        traffic: "",
        state: 1,
        userName: '',
        userPhone: '',
      },
      rules: {
        title: [{ required: true, message: "请输入上架标题", trigger: "blur" }],
        estateName: [{ required: true, validator: this.validEstate, trigger: "blur" }],
        houseNum: [{ required: true, message: "请输入栋阁房号", trigger: "blur" }],
        sup: [{ required: true, message: "请输入出售总价", trigger: "blur" }],
        builtArea: [{ required: true, message: "请输入建筑面积", trigger: "blur" }],
        insideArea: [{ required: true, message: "请输入套内面积", trigger: "blur" }],
        kind: [{ required: true, validator: this.validKind, trigger: "blur" }],
        builtYear: [{ required: true, message: "请输入建成年代", trigger: "blur" }],
        floor: [{ required: true, validator: this.validFloor, trigger: "blur" }],
        orientation: [{ required: true, message: "请选择房源朝向", trigger: "change" }],
        decoration: [{ required: true, message: "请选择装修类型", trigger: "change" }],
        purpose: [{ required: true, message: "请选择房源用途", trigger: "change" }],
        nature: [{ required: true, message: "请输入产权性质", trigger: "blur" }],
        propertyYear: [{ required: true, message: "请输入产权年限", trigger: "blur" }],
        tag1: [{ required: true, message: "是否精选好房", trigger: "change" }],
        tag2_1: [{ required: true, message: "房源满几年", trigger: "change" }],
        tag2_2: [{ required: true, message: "是否唯一", trigger: "change" }],
        tag3: [{ required: true, message: "是否红本在手", trigger: "change" }],
        tag4: [{ required: true, message: "是否有电梯", trigger: "change" }],
        tag5: [{ required: true, message: "是否能随时看房", trigger: "change" }],
        // img: [{ message: "请上传房源图片", trigger: "change" }],
        // imgList: [{ message: "请上传详情图片", trigger: "change" }],
        branch: [{ required: true, message: "请输入房源附近的线下门店", trigger: "blur" }],
        lights_desc: [{ message: "请输入房源亮点介绍", trigger: "blur" }],
        dec_desc: [{ message: "请输入房源装修介绍", trigger: "blur" }],
        kind_desc: [{ message: "请输入房源户型介绍", trigger: "blur" }],
        traffic: [{ message: "请输入房源附近交通介绍", trigger: "blur" }],
        userName: [{ validator: this.validName, trigger: "blur" }],
        userPhone: [{ validator: this.validPhone, trigger: "blur" }]
      },

      //图片类型
      types: {
        imgType: "",
        // detailImgType: "",
      },
    };
  },

  created() {
    let oj = {
      title: '房源列表',
      nav: '1-2',
    };
    this.$emit('isTitle', oj);
    this.areaData = [...Data];
    this.areaData.shift();
    for (let key of this.areaData) {
      key.children.shift();
    }
    // 判断是否编辑
    console.log(this.$route)
    if (this.$route.query.id) {
      this.isEdit = true;
      this.axios({
        method: 'get',
        url: this.baseUrl + '/getHousedetail',
        params: this.$route.query
      }).then(res => {
        console.log('res==>', res)
        if (res.data.code == 200) {
          let obj = res.data.data[0]
          this.ruleForm = {
            id: obj.id,
            title: obj.title,
            estateName: obj.estate.estateName,
            estateId: obj.estateId,
            houseNum: obj.houseNum,
            sup: obj.sup,
            builtArea: obj.builtArea,
            insideArea: obj.insideArea,
            kind1: obj.kind1,
            kind2: obj.kind2,
            kind3: obj.kind3,
            floor1: obj.floor.substring(0, 3),
            floor2: obj.floor.replace(/[^0-9]/ig, ""),
            orientation: obj.orientation,
            builtYear: obj.builtYear,
            decoration: obj.decoration,
            branch: obj.branch,
            purpose: obj.purpose,
            nature: obj.nature,
            propertyYear: obj.propertyYear,
            sellingTime: obj.sellingTime,
            tag1: obj.tag1,
            tag2_1: obj.tag2.substring(0, 2),
            tag2_2: obj.tag2 ? (obj.tag2.charAt(obj.tag2.length - 1) == '年' ? 0 : 1) : 0,
            tag3: obj.tag3,
            tag4: obj.tag4,
            tag5: obj.tag5,
            lights_desc: obj.lights_desc,
            dec_desc: obj.dec_desc,
            kind_desc: obj.kind_desc,
            traffic: obj.traffic,
            state: obj.state,
            userName: obj.userName,
            userPhone: obj.userPhone,
          };
        }
      }).catch(err => {
        console.log('err==>', err)
        this.$message.error(res.data.msg)
      })
    }

    this.loadAll()
    // console.log(this.areaData)
  },

  methods: {
    // 小区输入框的输入建议
    querySearch(queryString, cb) {
      var estateList = this.estateList;
      var results = queryString ? estateList.filter(this.createFilter(queryString)) : estateList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (estate) => {
        return (estate.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 获取所有小区名,地址和id
    loadAll() {
      this.axios({
        method: 'get',
        url: this.baseUrl + '/getEstate',
      }).then(res => {
        console.log('res==>', res)
        if (res.data.code == 200) {
          // let arr = [];
          res.data.data.forEach(e => {
            let o = { "value": '', "address": '', "estateId": '' };
            o["value"] = e.estateName;
            o["address"] = e.address;
            o["estateId"] = e.estateId;
            // arr.push(o);
            this.estateList.push(o);
          });
          // console.log('arr==>', arr)
          // console.log('this.estateList==>', this.estateList)
        }
      }).catch(err => {
        console.log('err==>', err)

      })
      // return arr;
    },
    // 保存小区id
    handleSelect(item) {
      console.log(item);
      this.ruleForm.estateId = item.estateId;
    },
    // ----------------------------验证--------------------------------
    // 验证小区名
    validEstate(rule, value, callback) {
      if (!value) {
        callback(Error("请输入小区名或楼盘"))
      } else {
        callback();
      }
    },
    // 验证楼层
    validKind(rule, value, callback) {
      if (!this.ruleForm.kind1 || !this.ruleForm.kind2 || !this.ruleForm.kind3) {
        callback(Error("请输入户型"))
      } else {
        callback();
      }
    },
    // 验证楼层
    validFloor(rule, value, callback) {
      if (!this.ruleForm.floor1 || !this.ruleForm.floor2) {
        callback(Error("请选择楼层"))
      } else {
        callback();
      }
    },
    // 验证姓名
    validName(rule, value, callback) {
      if (this.ruleForm.userPhone === "") {
        callback();
        // callback(new Error("请输入姓名"));
      } else if (!/^[\u4e00-\u9fa5·]{2,5}|[a-zA-Z]$/.test(value)) {
        callback(new Error("姓名有误!"));
      }
    },
    // 验证手机号
    validPhone(rule, value, callback) {
      if (this.ruleForm.userName === "") {
        callback();
        // callback(new Error("请输入手机号"));
      } else if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        callback(new Error("手机格式错误!"));
      }
    },
    // ----------------------------验证--------------------------------
    //上传文件
    upload(e, key) {
      console.log("e ==> ", e);
      this.ruleForm[key] = e.base64;
      this.types[key + "Type"] = e.type;
      // console.log(this.types)
      // console.log(this.ruleForm)
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.ruleForm.estateId) {
            this.$message.warning("请输入有效的小区名或楼盘")
            return
          }
          // let house = Object.assign({}, this.ruleForm, this.types);
          this.ruleForm.img = this.ruleForm.img.replace(/^data:image\/[a-z]+;base64,/, "");
          // console.log('house.img ==> ', house.img);
          // house.detailImg = house.detailImg.replace(
          //   /^data:image\/[a-z]+;base64,/,
          //   ""
          // );
          console.log('form==>', this.ruleForm)
          //发起发布房源请求
          console.log('发起发布房源请求');
          this.axios({
            method: 'post',
            url: this.baseUrl + '/addHouse',
            data: {
              title: this.ruleForm.title,
              estateId: this.ruleForm.estateId,
              houseNum: this.ruleForm.houseNum,
              kind: this.ruleForm.kind1 + '室' + this.ruleForm.kind2 + '厅' + this.ruleForm.kind3 + '卫',
              sup: this.ruleForm.sup,
              builtArea: this.ruleForm.builtArea,
              insideArea: this.ruleForm.insideArea,
              sub: Math.round((Number(this.ruleForm.sup)) / (Number(this.ruleForm.builtArea)) * 10000),
              kind1: parseInt(this.ruleForm.kind1),
              kind2: parseInt(this.ruleForm.kind2),
              kind3: parseInt(this.ruleForm.kind3),
              floor: this.ruleForm.floor1 + '(共' + this.ruleForm.floor2 + '层)',
              orientation: this.ruleForm.orientation,
              builtYear: this.ruleForm.builtYear,
              decoration: this.ruleForm.decoration,
              branch: this.ruleForm.branch,
              purpose: this.ruleForm.purpose,
              nature: this.ruleForm.nature,
              propertyYear: this.ruleForm.propertyYear,
              sellingTime: new Date(),
              tag1: this.ruleForm.tag1,
              tag2: this.ruleForm.tag2_1 + (this.ruleForm.tag2_2 == 1 ? '唯一' : '年'),
              tag3: this.ruleForm.tag3,
              tag4: this.ruleForm.tag4,
              tag5: this.ruleForm.tag5,
              lights_desc: this.ruleForm.lights_desc,
              dec_desc: this.ruleForm.dec_desc,
              kind_desc: this.ruleForm.kind_desc,
              traffic: this.ruleForm.traffic,
              state: this.ruleForm.state,
              userName: this.ruleForm.userName,
              userPhone: this.ruleForm.userPhone,
              img: this.ruleForm.img,
              imgType: this.types.imgType
            },
          }).then(res => {
            console.log('res==>', res)
            if (res.data.code == 200) {
              this.$message.success('房源发布成功')
              this.$router.push({ name: 'B_HouseList' })
            } else {
              this.$message.error('房源发布失败')
            }
          }).catch(err => {
            console.log('err==>', err)
            this.$message.error(err)
          })
        } else {
          this.$message.warning('请完善资料!')
          return false;
        }
      });
    },
    // 保存信息
    saveEditData(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.ruleForm.estateId) {
            this.$message.warning("请输入有效的小区名或楼盘")
            return
          }
          let data = {
            id: this.ruleForm.id,
            title: this.ruleForm.title,
            estateId: this.ruleForm.estateId,
            houseNum: this.ruleForm.houseNum,
            kind: this.ruleForm.kind1 + '室' + this.ruleForm.kind2 + '厅' + this.ruleForm.kind3 + '卫',
            sup: this.ruleForm.sup,
            builtArea: this.ruleForm.builtArea,
            insideArea: this.ruleForm.insideArea,
            sub: Math.round((Number(this.ruleForm.sup)) / (Number(this.ruleForm.builtArea)) * 10000),
            kind1: parseInt(this.ruleForm.kind1),
            kind2: parseInt(this.ruleForm.kind2),
            kind3: parseInt(this.ruleForm.kind3),
            floor: this.ruleForm.floor1 + '(共' + this.ruleForm.floor2 + '层)',
            orientation: this.ruleForm.orientation,
            builtYear: this.ruleForm.builtYear,
            decoration: this.ruleForm.decoration,
            branch: this.ruleForm.branch,
            purpose: this.ruleForm.purpose,
            nature: this.ruleForm.nature,
            propertyYear: this.ruleForm.propertyYear,
            // sellingTime: new Date(),
            tag1: this.ruleForm.tag1,
            tag2: this.ruleForm.tag2_1 + (this.ruleForm.tag2_2 == 1 ? '唯一' : '年'),
            tag3: this.ruleForm.tag3,
            tag4: this.ruleForm.tag4,
            tag5: this.ruleForm.tag5,
            lights_desc: this.ruleForm.lights_desc,
            dec_desc: this.ruleForm.dec_desc,
            kind_desc: this.ruleForm.kind_desc,
            traffic: this.ruleForm.traffic,
            state: this.ruleForm.state,
            userName: this.ruleForm.userName,
            userPhone: this.ruleForm.userPhone,
          };
          this.axios({
            method: 'post',
            url: this.baseUrl + '/editHouse',
            data: data
          }).then(res => {
            console.log('res==>', res)
            if (res.data.code == 200) {
              this.$message.success('保存房源信息成功')
              if (this.ruleForm.state == 0) {
                this.$router.push({ name: 'B_CheckHouse' })
              } else {
                this.$router.push({ name: 'B_HouseList' })
              }
            } else {
              this.$message.error('保存房源信息失败')
            }
          }).catch(err => {
            console.log('err==>', err)
            this.$message.error(res.data.msg)
          })

        } else {
          this.$message.warning('请完善资料!')
          return false;
        }
      })
    }
  },

  components: {
    UploaderFile
  }
};
</script>
